import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:sports_new/entity/pay/coin_history_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/server/api/pay_api.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';

import '../../widgets/base/qkd_text.dart';
import '../../widgets/header_delegate.dart';

class MyCoinHistoryPage extends StatefulWidget {
  const MyCoinHistoryPage({super.key});

  @override
  State<MyCoinHistoryPage> createState() => _MyCoinHistoryPageState();
}

class _MyCoinHistoryPageState extends State<MyCoinHistoryPage> {
  List<DateTime>? dateList;
  List<List<CoinHistoryEntity>>? groupCoinList;
  int page = 1;
  int pageSize = 10;
  bool isLoading = true;
  List<CoinHistoryEntity>? list;
  final refresh = EasyRefreshController(controlFinishLoad: true);

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      getNew();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Styles.appBar(title: QkdText('球币明细')),
      backgroundColor: Colours.scaffoldBg,
      body: EasyRefresh(
        controller: refresh,
        onRefresh: () async {
          await getData();
        },
        onLoad: () async {
          await getMore();
        },
        child: LoadingWidget<int>(
          isLoading: isLoading,
          noData: const NoDataWidget(needScroll: true),
          data: dateList?.length,
          child: () => listView(),
        ),
      ),
    );
  }

  listView() {
    return CustomScrollView(
      slivers: [
        ...List.generate(
          dateList?.length ?? 0,
          (index) => SliverMainAxisGroup(
            slivers: [
              SliverPersistentHeader(
                pinned: true,
                delegate: HeaderDelegate(
                  extent: 30,
                  child: Container(
                    color: Colours.scaffoldBg,
                    padding: const EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.centerLeft,
                    child: QkdText(
                      DateFormat.yM('zh_cn').format(dateList![index]),
                      color: Colours.grey66, fontSize: 12,
                    ),
                  )
                )
              ),
              SliverList(
                  delegate: SliverChildBuilderDelegate(
                    childCount: groupCoinList?[index].length ?? 0,
                    (context, i) => _cell(groupCoinList![index][i])
                  )
              )
            ]
          )
        )
      ],
    );
  }

  _cell(CoinHistoryEntity data) {
    // CoinHistoryEntity data = list![index];
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Get.toNamed(Routes.myCoinDetial, arguments: data.id);
      },
      child: Styles.card(
          height: 80,
          padding: EdgeInsets.symmetric(horizontal: 8),
          margin: EdgeInsets.only(left: 8, right: 8, bottom: 8),
          alignment: Alignment.center,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(children: [
                QkdText(data.memo ?? '', fontSize: 16),
                Spacer(),
                QkdText(
                  (data.goldSign == 1 ? '+' : '-') +
                    (data.goldChange!.toStringAsFixed(2)),
                  color: data.goldSign == 1 ? Colours.main : Colours.text,
                  fontSize: 16,
                  fontWeight: FontWeight.w500
                ),
              ]),
              SizedBox(height: 4),
              Row(children: [
                QkdText(
                  DateTimeUtils.formatDateString(
                    data.createTime!, 'MM-dd HH:mm'),
                  color: Colours.grey66, fontSize: 12
                ),
                Spacer(),
                QkdText('余额 ${data.goldAfter!.toStringAsFixed(2)}',
                  color: Colours.grey66, fontSize: 12
                )
              ])
            ],
          )),
    );
  }

  getNew() async {
    page = 1;
    await getData();
  }

  getMore() async {
    page++;
    getData();
  }

  getData() async {
    final data = await PayApi.getCoinHistory(page, pageSize);
    if (data != null) {
      if (page == 1) {
        list = data;
        isLoading = false;
        handleData(list!);
        refresh.resetFooter();
      } else {
        list!.addAll(data);
        handleData(list!);
        if (data.length < pageSize) {
          refresh.finishLoad(IndicatorResult.noMore);
        } else {
          refresh.finishLoad(IndicatorResult.success);
        }
      }
    }
    update();
  }

  void handleData(List<CoinHistoryEntity> matchList) async {
    List<DateTime> dateListTemp = [];
    List<List<CoinHistoryEntity>> groupListTemp = [];
    List<CoinHistoryEntity> sameMonthCoinList = [];
    for (CoinHistoryEntity match in matchList) {
      final dateTime = DateTime.parse(match.createTime!).toLocal();
      if (dateListTemp.isEmpty) {
        dateListTemp.add(dateTime);
        sameMonthCoinList.add(match);
      } else if (DateUtils.isSameMonth(dateListTemp.last, dateTime)) {
        sameMonthCoinList.add(match);
      } else {
        groupListTemp.add(sameMonthCoinList);
        dateListTemp.add(dateTime);
        sameMonthCoinList = [match];
      }
    }
    //加上最后一个月比赛
    if (sameMonthCoinList.isNotEmpty) {
      groupListTemp.add(sameMonthCoinList);
    }

    dateList = dateListTemp;
    groupCoinList = groupListTemp;
    isLoading = false;
    update();
  }
}
